dict1 = {"a": 1}
print(dict1.get("a"))  # 1
print(dict1['a'])  # 1

print("====" * 100)


class Descriptor:

    def __init__(self, name):
        self.name = name

    def __get__(self, instance, owner):
        print("__get__")
        return instance.__dict__.get(self.name)

    def __set__(self, instance, value):
        print("__set__")
        instance.__dict__[self.name] = value


class C:
    x = Descriptor("x")


c = C()
result = c.x  # __get__
print(result)  # None
print(c.__dict__)  # {}

c.x = 250  # __set__

result = c.x  # __get__
print(result)  # 250
print(c.__dict__)  # {'x': 250}

# 上面的代码不够优雅，优化代码在下面
print("====" * 100)


class BetterDescriptor:

    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, instance, owner):
        print("__get__")
        return instance.__dict__.get(self.name)

    def __set__(self, instance, value):
        print("__set__")
        instance.__dict__[self.name] = value


class BetterC:
    x = BetterDescriptor()


betterC = BetterC()
r1 = betterC.x  # __get__
print(r1)  # None
print(betterC.__dict__)  # {}

betterC.x = 250  # __set__
r2 = betterC.x  # __get__
print(r2)  # 250
print(betterC.__dict__)  # {'x': 250}
